package gold.digger;

import gold.utils.InputUtil;

import java.util.Arrays;
import java.util.Comparator;

/**
 * Created by fanzhenyu02 on 2021/12/10.
 * common problem solver template.
 */
public class LC1024 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public int videoStitching(int[][] clips, int time) {
            Arrays.sort(clips, new Comparator<int[]>() {
                @Override
                public int compare(int[] o1, int[] o2) {
                    return o1[0] - o2[0];
                }
            });

            int n = clips.length, cnt = 1, curChoosePos = 0, nextChoosePos = 1;
            if (clips[0][0] > 0) return -1;
            for (int i = 1; i < n; i++) {
                if (clips[i][0] > 0) break;
                if (clips[i][1] > clips[curChoosePos][1]) curChoosePos = i;
            }

            nextChoosePos = curChoosePos + 1;
            while (curChoosePos < n && clips[curChoosePos][1] < time) {
                if (nextChoosePos >= n || clips[nextChoosePos][0] > clips[curChoosePos][1]) return -1;
                int curNextMaxPos = nextChoosePos;
                for (; nextChoosePos < n && clips[nextChoosePos][0] <= clips[curChoosePos][1]; ++nextChoosePos) {
                    if (clips[nextChoosePos][1] > clips[curNextMaxPos][1]) curNextMaxPos = nextChoosePos;
                }
                curChoosePos = curNextMaxPos;
                nextChoosePos = curChoosePos + 1;
                cnt++;
                if (clips[curChoosePos][1] >= time) return cnt;
            }

            return cnt;
        }
    }

    public void run() {
        Solution solution = new Solution();
        System.out.println(solution.videoStitching(InputUtil.toDoubleIntegerArray("[[0,2],[4,6],[8,10],[1,9],[1,5],[5,9]]"), 10));
        System.out.println(solution.videoStitching(InputUtil.toDoubleIntegerArray("[[0,1],[1,2]]"), 5));
        System.out.println(solution.videoStitching(InputUtil.toDoubleIntegerArray("[[0,1],[6,8],[0,2],[5,6],[0,4],[0,3],[6,7],[1,3],[4,7],[1,4],[2,5],[2,6],[3,4],[4,5],[5,7],[6,9]]"), 9));
        System.out.println(solution.videoStitching(InputUtil.toDoubleIntegerArray("[[0,4],[2,8]]"), 5));
        System.out.println(solution.videoStitching(InputUtil.toDoubleIntegerArray("[[1,1],[0,2]]"), 2));
    }

    public static void main(String[] args) throws Exception {
        LC1024 an = new LC1024();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
